﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using static System.Net.Mime.MediaTypeNames;

namespace ArithmeticOne
{
    public class Program
    {
        static string TopicPath = Directory.GetCurrentDirectory().Split("\\bin").FirstOrDefault() + @"\CreateFiles\Topic.txt";
        public static void Main(string[] args)
        {
            var arg = "-Read";

            if (arg == "-w")
            {
                WriteTextFile();//使用文件流写入文件
            }
            else if (arg == "-sample")
            {
                //新建文件
                CreateSampleFileAsync(30).Wait();
            }
            else if (arg == "-Read")
            {
                //读文件
                ReadFileUsingFileStream(TopicPath, out List<dynamic> Topics);
                foreach (var item in Topics)
                {
                    Console.WriteLine($"{item.Number}.{item.Topic} {item.Answer}");
                }
            }

            WriteXmlDoc("one.xml",10);
            Console.WriteLine("ready");
        }
        public static void WriteTextFile()
        {
            //创建临时文件，并将扩展名更名为txt
            string tempTextFileName = Path.ChangeExtension(Path.GetTempFileName(), "txt");

            using (FileStream stream = File.OpenWrite(tempTextFileName))
            {
                //// write BOM--效果同下节
                //stream.WriteByte(0xef);
                //stream.WriteByte(0xbb);
                //stream.WriteByte(0xbf);

                //指定编码的字节序列存入preamble。
                byte[] preamble = Encoding.UTF8.GetPreamble();
                //将编码信息写入流
                stream.Write(preamble, 0, preamble.Length);

                //生成字符串
                string hello = "Hello, World!";
                //存储字符串UTF-8编码字节块
                byte[] buffer = Encoding.UTF8.GetBytes(hello);
                //将字节块写入流
                stream.Write(buffer, 0, buffer.Length);
                //输出文件名
                Console.WriteLine($"file {stream.Name} written");
            }
        }
  



        public static async Task CreateSampleFileAsync(int count)
        {

            using (FileStream stream = File.Create(TopicPath))
            using (var writer = new StreamWriter(stream))
            {
                var records = Enumerable.Range/*生成一个序列(范围)*/(1, count).Select(x => new
                {
                    Number = x,
                    Topic = GetTopic(out int value),
                    Answer = value
                });
                foreach (var rec in records)
                {
                    string s = $"{rec.Number}#{rec.Topic}#{rec.Answer}{Environment.NewLine}";
                    await writer.WriteAsync(s);//已异步的方式写入FileStream
                }
            }
    
        }

        private static void WriteXmlDoc(string fileName, int count)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            using (XmlWriter writer = XmlWriter.Create("..\\..\\..\\" + fileName, settings))
            {
                writer.WriteStartElement("customer");
                //写属性
                writer.WriteAttributeString("id", "1");
                writer.WriteAttributeString("status", "archived");
                writer.WriteStartElement("请回答");
         

                var records = Enumerable.Range/*生成一个序列(范围)*/(1, count).Select(x => new
                {
                    Number = x,
                    Topic = GetTopic(out int value),
                    Answer = value
                });
                foreach (var rec in records)
                {
                    string s = $"{rec.Number}#{rec.Topic}#{rec.Answer}{Environment.NewLine}";
                    writer.WriteValue(s);;//已异步的方式写入FileStream
                }
            }
            Console.WriteLine("写入成功");
        }

        private static string GetTopic(out int value)
        {
            Random rd = new Random();
            int a = rd.Next(0, 10);
            int b = rd.Next(0, 10);
            int op = rd.Next(1, 3);
            char c = '+';
            value = 0;
            switch (op)
            {
                case 1: c = '+'; value = a + b; break;
                case 2: c = '-'; value = a - b; break;
            }
            return $"{a}{c}{b}=?";
        }

        private static void ReadingAFileLineByLine(string fileName)
        {
            string[] lines = File.ReadAllLines(fileName);
            int i = 1;
            foreach (var line in lines)
            {
                Console.WriteLine($"{i++}. {line}");
            }

            IEnumerable<string> lines2 = File.ReadLines(fileName);
            i = 1;
            foreach (var line in lines2)
            {
                Console.WriteLine($"{i++}. {line}");
            }
        }

        public static void ReadFileUsingFileStream(string fileName, out List<dynamic> Topics)
        {
            using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (var writer = new StreamReader(stream))
                {
                    Topics = new List<dynamic>();
                    string[] tops = new string[] { "Number", "Topic", "Answer" };
                    while (writer.Peek() > 0)
                    {
                        string[] topicSplit = writer.ReadLine().Split('#'); ;//读取文件中的一行字符                                                                             
                        dynamic dynamicEntity = new ExpandoObject();//构造一个成员未知的动态对象dynamicEntity
                        for (int i = 0; i < tops.Length; i++)
                        {
                            ((IDictionary<string, object>)dynamicEntity).Add(tops[i], topicSplit[i]);
                        }
                        Topics.Add(dynamicEntity);
                    }
                }
            }
        }
        public void Rechter(int value)
        {
            var s = Convert.ToInt32(Console.ReadLine());
            for (var i = 0; i < 10; i++)
            {
                if (s == value)
                {
                    Console.WriteLine("正确");
                }
                else
                {
                    Console.WriteLine("错误");
                }

            }
        }
    }
}